#include "voicectl_pkg/voicectrl.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>


#define FILENAMELEN  110
#define DIRNAME  100

char Filename[FILENAMELEN];
char Dirname[DIRNAME];
pid_t Pid;
char Flag = 0;

int Init_Voice_File_Route(const char* dirname)
{
   int len;
   FILE *fp ;
   char volumename[] = "volume";

   len = strlen(dirname);
   if(len > DIRNAME)
   {
      RCLCPP_WARN(node->get_logger(),"Directory name is too long!\n");
      return -1;
   }
   if(opendir(dirname) == NULL)
   {
      RCLCPP_WARN(node->get_logger(),"Directory is not exist!\n");
      return -2;
   }
   sprintf(Dirname,"%s",dirname);
   sprintf(Filename,"%s%s",dirname,volumename);

   return 0;
}

int Get_Volume(void)
{
	FILE *fp;
	char str[100];
	char i = 0,j = 0;
	char tmp[4];
	int volume = 0;
	int len;
	char order[40];
	char order1[20] = "amixer get Master >";
	sprintf(order,"%s%s",order1,Filename);
	system(order);

	RCLCPP_INFO(node->get_logger(),"order = %s\n",order);
	if((fp = fopen(Filename,"r")) == NULL)
	{
	    perror("fopen");
	    RCLCPP_WARN(node->get_logger(),"fopen music dir error!\n");
	    return -1;
	}
	while(fscanf(fp,"%s\n",str)!=EOF)
	{
	    if(i == 20)
	    {
	          while(str[j] != '%')
	          {
	                tmp[j] = str[j + 1];
	                j ++;
	          }
	          volume = atoi(tmp);
	    }
	    i ++;
	}
	fclose(fp);

	return volume;
}

void Set_Volume(int volume)
{
	float tmp;
	int trvolume;
	int num;
	char order[80];
	static int last_volumn = 0;

	volume = volume > 100 ? 100 : volume;
	tmp = (float)volume * 86 / 99.0;
	trvolume = (int)(tmp + 0.5);

	if(last_volumn != volume)
	{
		last_volumn = volume;

		sprintf(order,"%s %d%%", "amixer -q set 'Speaker Driver CH1'", trvolume);
		system(order);
		//printf("%s\n", order);
		sprintf(order,"%s %d%%", "amixer -q set 'Speaker Driver CH2'", trvolume);
		system(order);
		sprintf(order,"%s %d%%", "amixer -q set 'Speaker Driver CH3'", trvolume);
		system(order);
		sprintf(order,"%s %d%%", "amixer -q set 'Speaker Driver CH4'", trvolume);
		system(order);
	}
}

#if 0
void Stop_Voice(void)
{
   if(Flag != 0)
   {
      kill(Pid,9);
   }
}
#endif

int Play_Voice(const char* voice) //yyy 2020-10-14 v3.1.2
{
	char buf[100] = {0};
	//Stop_Voice();  //先关闭已经打开的语音线程，防止语音重叠
	//Flag = 1;
	Pid = fork();

	if(Pid == 0)
	{
		sprintf(buf,"%s%s",Dirname,voice);
		execlp("play","play","-q",buf,NULL);  //指令：play -q 语音文件
		perror("execlp");
		exit(0);
	}

    return 0;
}

#if 0
void Pause_Continue_Voice(void)
{
   if(Flag == 1)
   {
		kill(Pid,19);
		Flag = 2;
   }
   else if(Flag == 2)
   {
		kill(Pid,18);
		Flag = 1;
   }
}
#endif



